﻿using AutoMapper;
using B.S.Orders.Domain;
using B.S.Orders.ErrorCord;
using B.S.Orders.Write.Api.Application.Command.OutsourcingCommand;
using MediatR;
using SqlSugar;

namespace B.S.Orders.Write.Api.Application.CommandHander.OutsourcingCommandHandler
{
    public class AddOutsourcingCommandHandler : IRequestHandler<AddOutsourcingCommand, APIResult<object>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public AddOutsourcingCommandHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<APIResult<object>> Handle(AddOutsourcingCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code = APIEnum.success;
            result.Msg = "添加成功";

            // 获取当前年月
            string yearMonth = DateTime.Now.ToString("yyyyMMddHHmmss");
            string prefix = "SCWW" + yearMonth;

            var model = mapper.Map<Outsourcing>(request);

            model.DocumentNumber = prefix;
            // 使用 ExecuteReturnIdentityAsync 方法插入数据并返回自增主键
            int OutsourcingId = await db.Insertable(model).ExecuteReturnIdentityAsync();

            // 将主键添加到结果中
            result.Data = new { OutsourcingId };

            return await Task.FromResult(result);
        }
    }
}
